package com.golddaymicromall.activity.storemanager;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.golddaymicromall.activity.R;
import com.golddaymicromall.base.BaseActivity;
import com.golddaymicromall.bean.StoreDetailInfo;
import com.golddaymicromall.util.RopUtils;
import com.golddaymicromall.util.SPUtils;
import com.golddaymicromall.util.ServerConfig;
import com.google.common.collect.Maps;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.convert.StringConvert;
import com.lzy.okrx.RxAdapter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import rx.android.schedulers.AndroidSchedulers;

public class StoreManagerActivity extends BaseActivity implements View.OnClickListener {

    //工具类
    private List<StoreDetailInfo> storeDetail;
    //控件类
    private TextView mStoreNo;
    private TextView mStoreProvince;
    private TextView mStoreType;
    private TextView mStoreRegDate;
    private TextView mstoreTurnDate;
    private LinearLayout mStoreBack;
    //参数类
    private String logid;
    private String provinceId;
    private String cityId;
    private String areaId;
    private String shop_Grade;
    private String IsShop;

    private String OrganizationId;
    private GridView gridView;
    SimpleAdapter saImageItems;
    ArrayList<HashMap<String, Object>> lstImageItem;
    HashMap<String, Object> map1;
    HashMap<String, Object> map6;
    HashMap<String, Object> map2;
    HashMap<String, Object> map3;
    HashMap<String, Object> map4;
    HashMap<String, Object> map5;
    HashMap<String, Object> map7;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_store_manager);
        OrganizationId = SPUtils.get(getApplicationContext(), "OrganizationId", "").toString();
        initView();
    }

    private void attemptStoreDetail() {
        //获取本地数据
        logid = SPUtils.get(getApplicationContext(), "Id", "").toString();

        Map<String, String> form = Maps.newHashMap();
        form.put("method", "rop.customer.get");
        form.put("appKey", "00001");
        form.put("v", "1.0");
        form.put("format", "json");
        form.put("id", logid);
        String sing = RopUtils.signString(form, "qwertyuiop");
        form.put("sign", sing);

        OkGo.post(new ServerConfig().SERVER)
                .params(form)
                .getCall(StringConvert.create(), RxAdapter.<String>create())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(result -> {
                    if (!"".equals(result)) {
                        if (result.contains("errorToken") || "0".equals(result)) {
                            Toast.makeText(getApplicationContext(), "访问服务器失败,请稍后重试", Toast.LENGTH_SHORT).show();
                        } else if ("null".equals(result)) {
                            Toast.makeText(getApplicationContext(), "暂无数据", Toast.LENGTH_SHORT).show();
                        } else {
                            storeDetail = JSON.parseArray(result, StoreDetailInfo.class);
                            SPUtils.put(StoreManagerActivity.this, "Grade", storeDetail.get(0).getGrade());
                            mStoreNo.setText(storeDetail.get(0).getCustomerno() + "(" + storeDetail.get(0).getUsername() + ")");
                            mStoreProvince.setText(storeDetail.get(0).getProvince1());
                            mStoreType.setText(storeDetail.get(0).getShoptype());
                            mStoreRegDate.setText(storeDetail.get(0).getRegdatestr());
                            shop_Grade = storeDetail.get(0).getShop_Grade();
                            mstoreTurnDate.setText(storeDetail.get(0).getTurndate());
                            provinceId = storeDetail.get(0).getProvince();
                            cityId = storeDetail.get(0).getCity();
                            areaId = storeDetail.get(0).getArea();
                            IsShop = storeDetail.get(0).getIsshopcenter();
                            com.golddaymicromall.util.Log.e("IsShop",IsShop);
                            com.golddaymicromall.util.Log.e("shop_Grade",shop_Grade);
                            initData();
                        }
                    } else {
                        Toast.makeText(getApplicationContext(), "没有请求到数据,请稍后重试", Toast.LENGTH_SHORT).show();
                        mStoreNo.setText("暂无网络");
                        mStoreProvince.setVisibility(View.GONE);
                        mStoreType.setVisibility(View.GONE);
                        mStoreRegDate.setVisibility(View.GONE);
                    }
                },throwable -> {
                    showError();
                    throwable.printStackTrace();
                });

    }


    private void attemptShengzhongxindian() {
        //获取本地数据
        logid = SPUtils.get(getApplicationContext(), "Id", "").toString();
        Map<String, String> form = Maps.newHashMap();
        form.put("method", "rop.customer.applystore");
        form.put("appKey", "00001");
        form.put("v", "1.0");
        form.put("format", "json");
        form.put("logid", logid);
        form.put("area", areaId);
        String sing = RopUtils.signString(form, "qwertyuiop");
        form.put("sign", sing);

        OkGo.post(new ServerConfig().SERVER)
                .params(form)
                .getCall(StringConvert.create(),RxAdapter.<String>create())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(result -> {
                    if (!"".equals(result)) {
                        if (result.contains("errorToken") || "0".equals(result)) {
                            Toast.makeText(getApplicationContext(), "访问服务器失败,请稍后重试", Toast.LENGTH_SHORT).show();
                        } else if ("null".equals(result)) {
                            Toast.makeText(getApplicationContext(), "暂无数据", Toast.LENGTH_SHORT).show();
                        } else {
                            if (Integer.parseInt(result) == 1 || Integer.parseInt(result) == 2) {
                                Toast.makeText(StoreManagerActivity.this, "申请中心店成功", Toast.LENGTH_SHORT).show();
                                IsShop = "1";
                                attemptStoreDetail();
                                initData();
                            } else if (Integer.parseInt(result) == -1) {
                                Toast.makeText(StoreManagerActivity.this, "该区域已经有中心店", Toast.LENGTH_SHORT).show();
                            } else if (Integer.parseInt(result) == 0) {
                                Toast.makeText(StoreManagerActivity.this, "申请中心店失败", Toast.LENGTH_SHORT).show();
                            }
                        }
                    } else {
                        Toast.makeText(getApplicationContext(), "没有请求到数据,请稍后重试", Toast.LENGTH_SHORT).show();
                    }
                },throwable -> {
                    showError();
                    throwable.printStackTrace();
                });

    }

    public void initView() {
        mStoreNo = (TextView) findViewById(R.id.storeNo);
        mstoreTurnDate = (TextView) findViewById(R.id.storeTurnDate);
        mStoreProvince = (TextView) findViewById(R.id.storeProvince);
        mStoreType = (TextView) findViewById(R.id.storeType);
        mStoreRegDate = (TextView) findViewById(R.id.storeRegDate);
        mStoreBack = (LinearLayout) findViewById(R.id.store_back);
        gridView = (GridView) findViewById(R.id.gridview);

        mStoreBack.setOnClickListener(this);
    }

    private void initData() {
        //生成动态数组，并且转入数据
        lstImageItem = new ArrayList<HashMap<String, Object>>();
        map1 = new HashMap<String, Object>();
        map1.put("ItemImage", R.drawable.ic_xiaoshouguanli_xiangqing);//添加图像资源的ID
        map1.put("ItemText", "店铺详情");
        lstImageItem.add(map1);
        map2 = new HashMap<String, Object>();
        map2.put("ItemImage", R.drawable.ic_xiaoshouguanli_tianjia);//添加图像资源的ID
        map2.put("ItemText", "添加店铺");
        lstImageItem.add(map2);
        map3 = new HashMap<String, Object>();
        map3.put("ItemImage", R.drawable.ic_xiaoshouguanli_bianji);//添加图像资源的ID
        map3.put("ItemText", "编辑店铺信息");
        lstImageItem.add(map3);
        map4 = new HashMap<String, Object>();
        map4.put("ItemImage", R.drawable.ic_xiaoshouguanli_chongzhi);//添加图像资源的ID
        map4.put("ItemText", "加盟类型变更");
        lstImageItem.add(map4);
        map5 = new HashMap<String, Object>();//
        map5.put("ItemImage", R.drawable.ic_zhengce);//添加图像资源的ID
        map5.put("ItemText", "店铺政策");
        lstImageItem.add(map5);

        if (!"1".equals(IsShop) && "2".equals(shop_Grade)) {
            map6 = new HashMap<String, Object>();
            map6.put("ItemImage", R.drawable.ic_zhongxindian);//
            map6.put("ItemText", "申请中心店");
            lstImageItem.add(map6);
        }
        if (!"28".equals(OrganizationId)) {
            if ("29".equals(OrganizationId)) {
                map7 = new HashMap<String, Object>();
                map7.put("ItemImage", R.drawable.ic_tepi);//添加图像资源的ID
                map7.put("ItemText", "特聘管理办法");
                lstImageItem.add(map7);
            } else {
                map7 = new HashMap<String, Object>();
                map7.put("ItemImage", R.drawable.ic_tepi);//添加图像资源的ID
                map7.put("ItemText", "申请特聘");
                lstImageItem.add(map7);
            }
        }
        //生成适配器的ImageItem <====> 动态数组的元素，两者一一对应
        saImageItems = new SimpleAdapter(StoreManagerActivity.this, //没什么解释
                lstImageItem,//数据来源
                R.layout.dianpuguanli_gridview_item,//night_item的XML实现
                //动态数组与ImageItem对应的子项
                new String[]{"ItemImage", "ItemText"},
                //ImageItem的XML文件里面的一个ImageView,两个TextView ID
                new int[]{R.id.ItemImage, R.id.ItemText});
        //添加并且显示
        gridView.setAdapter(saImageItems);
        //添加消息处理
        gridView.setOnItemClickListener(new ItemClickListener());
    }

    //当AdapterView被单击(触摸屏或者键盘)，则返回的Item单击事件
    class ItemClickListener implements AdapterView.OnItemClickListener {
        public void onItemClick(AdapterView<?> arg0,//The AdapterView where the click happened
                                View arg1,//The view within the AdapterView that was clicked
                                int arg2,//The position of the view in the adapter
                                long arg3//The row id of the item that was clicked
        ) {
            String Id = SPUtils.get(StoreManagerActivity.this, "Id", "").toString();
            //在本例中arg2=arg3
            HashMap<String, Object> item = (HashMap<String, Object>) arg0.getItemAtPosition(arg2);
            //显示所选Item的ItemText
            switch ((String) item.get("ItemText")) {

                case "店铺详情":
                    Intent intent_detail = new Intent(StoreManagerActivity.this, StoreDetailActivity.class);
                    startActivity(intent_detail);
                    break;
                case "添加店铺":
                    Intent intent_add = new Intent(StoreManagerActivity.this, StoreAddActivity.class);
                    startActivity(intent_add);
                    break;
                case "编辑店铺信息":
                    Intent intent_update = new Intent(StoreManagerActivity.this, StoreUpdateActivity.class);
                    intent_update.putExtra("provinceId", provinceId);
                    intent_update.putExtra("cityId", cityId);
                    intent_update.putExtra("areaId", areaId);
                    startActivity(intent_update);
                    break;
                case "加盟类型变更":
                    if (shop_Grade == null) {
                        return;
                    }
                    if (shop_Grade.equals("2")) {
                        Toast.makeText(StoreManagerActivity.this, "您已是最高级别店铺", Toast.LENGTH_SHORT).show();
                        return;
                    } else if (!"".equals(mstoreTurnDate.getText())) {
                        Toast.makeText(StoreManagerActivity.this, "您的店铺已经激活,无法使用该功能", Toast.LENGTH_SHORT).show();
                        return;
                    } else {
                        Intent intent_editType = new Intent(StoreManagerActivity.this, StoreEditTypeActivity.class);
                        startActivity(intent_editType);
                    }
                    break;
                case "申请特聘":
                    Intent toShengQingTEPin = new Intent(StoreManagerActivity.this, ShengQingTePinActivity.class);
                    startActivity(toShengQingTEPin);
                    break;
                case "特聘管理办法":
                    Intent toShengQingTEPin1 = new Intent(StoreManagerActivity.this, ShengQingTePinActivity.class);
                    startActivity(toShengQingTEPin1);
                    break;
                case "申请中心店":
                    if ("".equals(mstoreTurnDate.getText())) {
                        Toast.makeText(StoreManagerActivity.this, "您的店铺还未激活", Toast.LENGTH_SHORT).show();
                        return;
                    } else if (!"2".equals(shop_Grade)) {
                        Toast.makeText(StoreManagerActivity.this, "您的店铺不是专营店", Toast.LENGTH_SHORT).show();
                        return;
                    } else if ("1".equals(IsShop)) {
                        Toast.makeText(StoreManagerActivity.this, "您已经申请中心店", Toast.LENGTH_SHORT).show();
                        return;
                    } else {
                        attemptShengzhongxindian();
                    }
                    break;
                case "店铺政策":
                    Intent intentDianpuzhengce = new Intent(StoreManagerActivity.this, DianPuZhenCeActivity.class);
                    startActivity(intentDianpuzhengce);
                    break;
                default:
                    break;
            }
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.store_back:
                finish();
                break;
            default:
                break;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onResume() {
        super.onResume();
        this.attemptStoreDetail();
        initData();
    }
}
